package utils

import (
	"fmt"
	"html/template"
	"io"
	"strings"
)

func tmpl(f string) string {
	return fmt.Sprintf("tmpl/%s.html", f)
}

func lyt(f string) string {
	return fmt.Sprintf("layout/%s.html", f)
}

func ParseTmpl(f string, side bool) Tmpl {
	if !side {
		t, err := template.ParseFiles(tmpl(f))
		Must(err)
		return Tmpl{f, t}
	} else {
		t, err := template.ParseFiles(tmpl(f), lyt("imports"), lyt("nav"))
		Must(err)
		return Tmpl{f, t}
	}
}

type Tmpl struct {
	f string
	t *template.Template
}

func (t Tmpl) Exc(wr io.Writer, data any) {
	dt := data
	switch dtt := data.(type) {
	case Data:
		dtt.ImpPrefix = strings.Repeat("../", strings.Count(t.f, "/"))
		dt = dtt
	}
	Must(t.t.Execute(wr, dt))
}
